package com.fjl.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.exception.NoApiKeyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Slf4j
@RestController("/baiLian")
public class BaiLianController {


    @Value("${ali.bailian.api-key}")
    private String apiKey;
    @Value("${ali.bailian.text.to.img.model}")
    private String textToImgModel;
    @Value("${ali.bailian.text.to.audio.model}")
    private String textToAudioModel;

    @Autowired
    private ChatModel chatModel;
    @Autowired
    private ChatClient chatClient;
 
    @RequestMapping("/chat/model")
    public String chatModel(@RequestParam("message") String message){
        return chatModel.call(message);
    }
 
    @RequestMapping("/chat/client")
    public String chatClient(String message){
        return chatClient.prompt(message).call().content();
    }

    /**
     * 文生图片
     */

    @RequestMapping("/text/img")
    public List<String> textToImg(@RequestParam(name = "msg") String msg,
                                  @RequestParam(name = "n", required = false, defaultValue = "1") Integer n,
                                  @RequestParam(name = "size", required = false, defaultValue = "1024*1024") String size) throws NoApiKeyException {
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .apiKey(apiKey)         // api-key
                .model(textToImgModel)  // 文生图模型名称
                .prompt(msg)            // 提示词
                .n(n)                   // 生成几张
                .size(size)             // 图片尺寸
                .build();
        ImageSynthesis imageSynthesis = new ImageSynthesis();   // 图片合成器
        return imageSynthesis.call(param).getOutput().getResults().stream().map(r -> r.get("url")).collect(Collectors.toList());
    }



    /**
     * 文生音频
     */
    @RequestMapping("/text/audio")
    public String textToAudio(@RequestParam(name = "msg") String msg){
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(apiKey)             // api-key
                .model(textToAudioModel)    // 模型名称
                .text(msg)                  // 提示词
                .build();
        SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(); // 音频合成器
        ByteBuffer audioByte = speechSynthesizer.call(param);
        String fileName = "./百炼文生音频-"+ UUID.randomUUID() + ".mp3";
        File file = new File(fileName);
        try (FileOutputStream fos = new FileOutputStream(file)){
            fos.write(audioByte.array());
        }catch (Exception e){
            log.error("AliBaiLianController textToAudio error ", e);
        }
        return fileName;
    }
    // 定义一个消息列表，存储所有的对话内容
    List<Message> messages = new ArrayList<>();
    /**
     * 助手消息聊天
     */
    @RequestMapping("/assistant/chat")
    public String assistantChat(String msg){
        // 加入用户当前的内容
        messages.add(new UserMessage(msg));
        // 大模型回答后的消息内容，就是一个“助手消息”类型
        AssistantMessage assistantMessage = chatClient.prompt()
                .messages(messages)     // 传入所有的消息内容
                .call().chatResponse().getResult().getOutput();
        // 把大模型的回复信息也加入到消息列表中，下次再提问大模型时就可以将“以前”的消息一并发送给大模型
        messages.add(assistantMessage);
        return assistantMessage.getText();
    }

}